package main.java.leetcode.简单;

import org.junit.Test;

public class leetcode121_买卖股票 {

    /**
     * 最大利润 官方
     * @param prices
     * @return
     */
    public int maxProfitG(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

    /**
     * 股票利润 取最小值
     */
    public int maxProfitMin(int[] prices) {
        int max = 0;
        int minPrice = Integer.MAX_VALUE;

        for (int i = 0;i<prices.length;i++){
            if (prices[i]<minPrice){
                minPrice = prices[i];
            }else {
                if (prices[i]-minPrice>max){
                    max = prices[i] - minPrice;
                }
            }
        }
        return max;
    }

    /**
     * 股票最大利润 - 暴力破解
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0;i<prices.length-1;i++){
            for(int j = i+1;j<prices.length;j++){
                int result = prices[j]-prices[i];
                if(result>max){
                    max = result;
                }
            }
        }
        return max;
    }

    /**
     * 股票利润 二分
     */
    public int maxProfitTwo(int[] prices) {
        int min =  9999;
        int max =  0;

        for (int i = 0;i<prices.length;i++){
            if(min>prices[i]){
                min = prices[i];
            }else if (max<(prices[i]-min)){
                max = prices[i]-min;
            }
        }
        return max;

    }


    @Test
    public void maxProfitTest(){
        int[] profit = new int[]{2,4,1};
//        System.out.println(maxProfitMin(profit));
//        System.out.println(maxProfitG(profit));
        System.out.println(maxProfitTwo(profit));
    }





}
